<template>
  <view>
    <u-empty style="width: 640rpx" v-if="!fileSource" mode="data" icon="/static/empty/data.png"></u-empty>
    <block v-for="(item, index) in fileSource.fileData" :key="item.name">
      <!-- 附件列表 -->
      <view class="file">
        <image
          src="@/static/synergy/pdf.png"
          v-if="item.type == '.pdf' || item.type == '.PDF'"
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          src="@/static/synergy/excel.png"
          v-else-if="item.type == '.xlsx' || item.type == '.xls' || item.type == '.xlsm' || item.type == '.xlsb'"
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          @click="onViewImage(item.url)"
          src="@/static/synergy/image.png"
          v-else-if="
            item.type == '.png' ||
            item.type == '.jpg' ||
            item.type == '.jpeg' ||
            item.type == '.gif' ||
            item.type == '.bmp' ||
            item.type == '.webp'
          "
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          src="@/static/synergy/video.png"
          v-else-if="
            item.type == '.video' ||
            item.type == '.AVI' ||
            item.type == '.mov' ||
            item.type == '.rmvb' ||
            item.type == '.rm' ||
            item.type == '.FLV' ||
            item.type == '.mp4' ||
            item.type == '.3GP'
          "
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          src="@/static/synergy/word.png"
          v-else-if="item.type == '.doc' || item.type == '.docx'"
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          src="@/static/synergy/zip.png"
          v-else-if="item.type == '.rar' || item.type == '.zip'"
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image
          src="@/static/synergy/ppt.png"
          v-else-if="item.type == '.ppt' || item.type == '.pptx'"
          mode="aspectFill"
          class="file_image1"
        ></image>
        <image src="@/static/synergy/other.png" mode="aspectFill" v-else class="file_image1"></image>
        <!-- 图片文件名称展示 -->
        <view
          class="file_content"
          @click="onViewImage(item.url)"
          v-if="
            item.type == '.png' ||
            item.type == '.jpg' ||
            item.type == '.jpeg' ||
            item.type == '.gif' ||
            item.type == '.bmp' ||
            item.type == '.webp'
          "
        >
          <view class="file_name" :style="flowList ? 'width: 456rpx' : ''">{{ item.name }}</view>
          <!-- <view class="file_size">{{ item.size }} &nbsp;&nbsp;&nbsp; {{ item.type }}</view> -->
          <!-- <view class="file_size">{{ item.type }}</view> -->
        </view>
        <view class="file_content" v-else>
          <view class="file_name" :style="flowList ? 'width: 354rpx' : ''">{{ item.name }}</view>
          <!-- <view class="file_size">{{ item.size }} &nbsp;&nbsp;&nbsp; {{ item.type }}</view> -->
          <!-- <view class="file_size">{{ item.type }}</view> -->
        </view>

        <view
          class="file_btn"
          v-if="
            item.type != '.png' ||
            item.type != '.jpg' ||
            item.type != '.jpeg' ||
            item.type != '.gif' ||
            item.type != '.bmp' ||
            item.type != '.webp'
          "
        >
          <view style="display: flex">
            <!-- <image src="@/static/synergy/download.png" mode="aspectFill" class="file_image2"></image> -->
            <u-icon v-if="isDownload" name="download" @click="download(item.url)" color="#1E6FFF" size="22"></u-icon>
            <u-icon name="eye" v-if="item.classify != 'image'" @click="preview(item.url)" color="#1E6FFF" size="22"></u-icon>
            <!-- <view v-if="!isDelete">下载</view> -->
          </view>
          <u-line v-if="isDelete" direction="col" length="20" margin="0 10rpx"></u-line>
          <u-icon @click="onDelete(item, index)" name="trash-fill" color="red" size="22" v-if="isDelete"></u-icon>
        </view>
      </view>
    </block>
    <template v-if="!flowList">
      <block v-if="!isDelete">
        <view class="image_lists" style="display: flex; flex-wrap: wrap" v-if="fileSource.imageData && fileSource.imageData.length">
          <view class="image_list" v-for="(val, ind) in fileSource.imageData" :key="val.name">
            <view class="image_img">
              <image :src="val.url" mode="aspectFill" class="image_source"></image>
              <image
                src="../../../static/synergy/watch.png"
                mode="aspectFill"
                class="image_action"
                @click="viewImage(val.url, ind)"
              ></image>
            </view>
            <view class="image_name">{{ val.name }}</view>
          </view>
        </view>
      </block>
      <block v-if="isDelete">
        <view class="image_lists" style="width: 100%" v-if="fileSource.imageData && fileSource.imageData.length">
          <view
            class="image_list"
            style="display: flex; width: 100%; justify-content: space-between; align-items: center"
            v-for="(val, ind) in fileSource.imageData"
            :key="val.name"
            @click="onDeleteImage(val, ind)"
          >
            <view class="">
              <view class="image_img">
                <image :src="val.url" mode="aspectFill" class="image_source"></image>
                <image
                  src="../../../static/synergy/watch.png"
                  mode="aspectFill"
                  class="image_action"
                  @click.stop="viewImage(val.url, ind)"
                ></image>
              </view>
              <view class="image_name">{{ val.name }}</view>
            </view>
            <u-icon name="trash-fill" color="red" size="22"></u-icon>
          </view>
        </view>
      </block>
    </template>
  </view>
</template>
<script>
import { getFillName } from '@/api/index.js'
import { imageUrl } from '@/utils/common.js'
export default {
  data() {
    return {
      fileSource: false,
    }
  },
  model: {
    prop: 'fileList',
    event: 'change',
  },
  props: {
    // 文件字符串，多个用逗号隔开
    fileList: {
      type: [String, Array],
      require: true,
    },
    // 是否是flowList文件使用此组件
    flowList: {
      type: Boolean,
      default: false,
    },
    isDelete: {
      type: Boolean,
      default: false,
    },
		// 默认展示下载按钮
		isDownload: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    fileList: {
      handler(val) {
        if (val) {
          // 判断是否为数组
          var fileListArr = ''
          if (Array.isArray(val)) {
            // 当是数组时
            fileListArr = []
            val.map((value) => {
              fileListArr.push(value.filePath)
            })
          } else {
            // 不是数组时
            fileListArr = val.split(',')
          }
          this.filterType(fileListArr)
        } else {
          this.fileSource = false
        }
      },
      immediate: true,
    },
  },
  methods: {
    // download() {
    // 	uni.downloadFile({
    // 		url: this.fileList.url,
    // 		success: (data) => {
    // 			if (data.statusCode === 200) {
    // 				//文件保存到本地
    // 				uni.saveFile({
    // 					tempFilePath: data.tempFilePath, //临时路径
    // 					success: function(res) {
    // 						uni.showToast({
    // 							icon: 'none',
    // 							mask: true,
    // 							title: '文件已保存：' + res.savedFilePath, //保存路径
    // 							duration: 3000,
    // 						});
    // 					}
    // 				});
    // 			}
    // 		},
    // 		fail: (err) => {
    // 			uni.showToast({
    // 				icon: 'none',
    // 				mask: true,
    // 				title: '失败请重新下载',
    // 			});
    // 		}
    // 	})
    // },
    // 预览图片
    viewImage(url, ind) {
      var urlArr = []
      this.fileSource.imageData.map((value) => {
        urlArr.push(value.url)
      })
      uni.previewImage({
        urls: urlArr,
        current: ind,
        longPressActions: {
          itemList: ['保存图片'],
          success: function (data) {
            uni.downloadFile({
              url: url,
              success: (result) => {
                if (result.statusCode === 200) {
                  //文件保存到本地
                  uni.saveImageToPhotosAlbum({
                    filePath: result.tempFilePath, //临时路径
                    success: function (ress) {
                      uni.showToast({
                        icon: 'none',
                        mask: true,
                        title: '文件已保存：' + ress.path, //保存路径
                        duration: 3000,
                      })
                    },
                  })
                }
              },
              fail: (err) => {
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '失败请重新下载',
                })
              },
            })
          },
          fail: function (err) {
            console.log(err.errMsg)
          },
        },
      })
    },
    onViewImage(url) {
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: ['保存图片'],
          success: function (data) {
            uni.downloadFile({
              url: url,
              success: (result) => {
                if (result.statusCode === 200) {
                  //文件保存到本地
                  uni.saveImageToPhotosAlbum({
                    filePath: result.tempFilePath, //临时路径
                    success: function (ress) {
                      uni.showToast({
                        icon: 'none',
                        mask: true,
                        title: '文件已保存：' + ress.path, //保存路径
                        duration: 3000,
                      })
                    },
                  })
                }
              },
              fail: (err) => {
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '失败请重新下载',
                })
              },
            })
          },
          fail: function (err) {
            console.log(err.errMsg)
          },
        },
      })
    },
    download(url) {
      var that = this
      // #ifndef APP-PLUS
      that.handleDownLoad(url)
      // #endif
      // #ifdef APP-PLUS
      that.downLoadApp(url)
      // #endif
    },
    // 预览
    preview(url) {
      uni.navigateTo({
        url: `/pages/previewFile/previewFile?url=${encodeURIComponent(url)}`,
      })
    },
    // 点击删除
    onDelete(item, index) {
      var _this = this
      var filePath = ''
      uni.showModal({
        title: '确定删除',
        content: '确定删除此附件？',
        success(res) {
          if (res.confirm) {
            _this.fileSource.fileData.splice(index, 1)
            if (_this.fileSource.fileData && _this.fileSource.fileData.length) {
              _this.fileSource.fileData.map((value, ind) => {
                filePath = value.path + ',' + filePath
              })
              filePath = filePath.substr(0, filePath.length - 1)
            }

            if (_this.fileSource.imageData && _this.fileSource.imageData.length) {
              _this.fileSource.imageData.map((value, ind) => {
                filePath = value.path + ',' + filePath
              })
              var reg = /,$/
              if (reg.test(filePath)) {
                filePath = filePath.substr(0, filePath.length - 1)
              }
            }
            _this.$emit('change', filePath)
          } else if (res.cancel) {
            // 用户点击取消
          }
        },
      })
    },

    // 点击删除图片
    onDeleteImage(item, index) {
      var _this = this
      var filePath = ''
      uni.showModal({
        title: '确定删除',
        content: '确定删除此图片？',
        success(res) {
          if (res.confirm) {
            _this.fileSource.imageData.splice(index, 1)
            if (_this.fileSource.imageData && _this.fileSource.imageData.length) {
              _this.fileSource.imageData.map((value, ind) => {
                filePath = value.path + ',' + filePath
              })
              filePath = filePath.substr(0, filePath.length - 1)
            }
            if (_this.fileSource.fileData && _this.fileSource.fileData.length) {
              _this.fileSource.fileData.map((value, ind) => {
                filePath = value.path + ',' + filePath
              })
              var reg = /,$/
              if (reg.test(filePath)) {
                filePath = filePath.substr(0, filePath.length - 1)
              }
            }
            _this.$emit('change', filePath)
          } else if (res.cancel) {
            // 用户点击取消
          }
        },
      })
    },

    // uniapp 原生api -- uni.downloadFile下载
    handleDownLoad(url) {
      uni.downloadFile({
        url: url,
        success: (result) => {
          if (result.statusCode === 200) {
            //文件保存到本地
            uni.saveFile({
              tempFilePath: result.tempFilePath, //临时路径
              success: function (ress) {
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '文件已保存：' + ress.savedFilePath, //保存路径
                  duration: 3000,
                })
              },
            })
            // 文件保存到本地
            uni.openDocument({
              filePath: result.tempFilePath,
              showMenu: true,
              success: function (res) {
                // 打开文档成功
              },
            })
          }
        },
        fail: (err) => {
          uni.showToast({
            icon: 'none',
            mask: true,
            title: '失败请重新下载',
          })
        },
      })
    },
    // H5+API定义的应用沙盒里的plus.downloader下载
    downLoadApp(url) {
      var name = url.split('static/').pop()
      let dtask = plus.downloader.createDownload(
        url,
        {
          //1.本地路径开头使用file://;
          //2.Android平台本地绝对路径为"storage/emulated/0",就是用户文件管理器能看到的了;
          //3.创建"xxx"作为文件夹名称，后缀是用于文件命名和格式修改，大家可以使用变量。
          filename: '_downloads/' + name, //利用保存路径，实现下载文件的重命名
        },
        function (d, status) {
          //d为下载的文件对象;status下载状态
          if (status == 200) {
            //下载成功
            //d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
            // let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
            // plus.runtime.openFile(d.filename); //选择软件打开文件
            uni.showToast({
              icon: 'none',
              mask: true,
              title: '文件已保存：' + d.filename, //保存路径
              duration: 2000,
            })
            this.timer = setTimeout(() => {
              clearTimeout(this.timer)
              this.timer = null
              // 文件保存到本地
              uni.openDocument({
                filePath: d.filename,
                showMenu: true,
                success: function (res) {
                  // 打开文档成功
                },
              })
            }, 2000)
          } else {
            //下载失败
            uni.showToast({
              icon: 'none',
              title: '下载失败',
              mask: true,
              duration: 2000,
            })
            plus.downloader.clear() //清除下载任务
          }
        },
      )
      dtask.start() //启用
    },

    async filterType(file) {
      // 文件数据存在
      var that = this
      if (file) {
        let fileList = file
        let imageArray = [] // 储存图片类型
        let fileArray = [] // 储存文件类型
        const reg = /\.(gif|jpg|jpeg|png|svg|bmp|webp|GIF|JPG|JPEG|PNG|SVG)$/
        for (var a = 0; a < fileList.length; a++) {
          let url = imageUrl(fileList[a])
          //---------------从后台解析文件名称 开始----------------
          let path = fileList[a]
          if (path.lastIndexOf('\\') >= 0) {
            let reg = new RegExp('\\\\', 'g')
            path = path.replace(reg, '/')
          }
          await getFillName({ fillName: path.substring(path.lastIndexOf('/') + 1) }).then((res) => {
            if (res.success) {
              if (reg.test(path)) {
                imageArray.push({
                  type: path.substring(path.lastIndexOf('.')),
                  // size: that.bytesToSize(data.size),
                  size: 0,
                  name: res.result,
                  url: imageUrl(path),
                  path: path,
                  classify: 'image',
                })
              } else {
                fileArray.push({
                  type: path.substring(path.lastIndexOf('.')),
                  // size: that.bytesToSize(data.size),
                  size: 0,
                  name: res.result,
                  url: imageUrl(path),
                  path: path,
                  classify: 'file',
                })
              }
            } else {
              if (reg.test(path)) {
                imageArray.push({
                  type: path.substring(path.lastIndexOf('.')),
                  // size: that.bytesToSize(data.size),
                  size: 0,
                  name: '',
                  url: imageUrl(path),
                  path: path,
                  classify: 'image',
                })
              } else {
                fileArray.push({
                  type: path.substring(path.lastIndexOf('.')),
                  // size: that.bytesToSize(data.size),
                  size: 0,
                  name: '',
                  url: imageUrl(path),
                  path: path,
                  classify: 'file',
                })
              }
            }
          })
          //---------------从后台解析文件名称 结束----------------
          if (that.flowList) {
            var fileArr = fileArray.concat(imageArray)
            that.fileSource = {
              fileData: fileArr,
            }
          } else {
            that.fileSource = {
              imageData: imageArray,
              fileData: fileArray,
            }
          }
        }
      } else {
        that.fileList = false
      }
    },
    async initFileList(paths) {},
    bytesToSize: function (size) {
      if (size < 1024) {
        //小于1KB，则转化成B
        size = size.toFixed(2) + 'B'
      } else if (size < 1024 * 1024) {
        // 小于1MB，则转化成KB
        size = (size / 1024).toFixed(2) + 'KB'
      } else if (size < 1024 * 1024 * 1024) {
        // 小于1GB，则转化成MB
        size = (size / (1024 * 1024)).toFixed(2) + 'MB'
      } else {
        // 其他转化成GB
        size = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }
      // 转成字符串
      let sizeStr = size + '',
        // 获取小数点处的索引
        index = sizeStr.indexOf('.'),
        // 获取小数点后两位的值
        dou = sizeStr.substr(index + 1, 2)
      // 判断后两位是否为00，如果是则删除00
      if (dou == '00') return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      return size
    },
  },
}
</script>
<style lang="scss" scoped>
.file {
  display: flex;
  padding: 24rpx 0;
  align-items: center;

  .file_image1 {
    width: 23px;
    height: 23px;
    margin-right: 10rpx;
  }

  .file_content {
    flex: 1;
    .file_name {
      font-size: 14px;
      // font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #7f7f7f;
      line-height: 14px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      max-width: 460rpx;
    }

    .file_size {
      font-size: 12px;
      // font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #c6c6c6;
      line-height: 14px;
      margin-top: 4rpx;
    }
  }

  .file_btn {
    display: flex;

    .file_image2 {
      width: 40rpx;
      height: 40rpx;
      margin-right: 4rpx;
    }

    view {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #1e6fff;
    }
  }
}

.image_lists {
  padding: 0 0 12rpx 12rpx;
  // display: flex;
  // flex-wrap: wrap;

  .image_list {
    margin-bottom: 20rpx;
    width: 144rpx;
    margin-right: 14rpx;

    .image_img {
      width: 116rpx;
      height: 116rpx;
      padding: 12rpx;
      background: rgba(0, 0, 0, 0.02);
      border-radius: 1px;
      border: 1px solid rgba(0, 0, 0, 0.08);
      position: relative;

      .image_action {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
        width: 36rpx;
        height: 36rpx;
      }

      .image_source {
        width: 100%;
        height: 100%;
      }
    }

    .image_name {
      font-size: 10px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #b2b2b2;
      line-height: 14px;
      margin-top: 8rpx;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      width: 152rpx;
    }
  }
}
</style>
